package Demo1.dao;

import Demo1.bean.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class StudentTest1 {
    @Test
    public void selectAll() throws Exception {
        //1.加载配置文件
        InputStream is = Resources.getResourceAsStream("MybatisConfig.xml");

        //2.获取工厂对象
        SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(is);

        //3.通过工厂对象回去SqlSession对象
        SqlSession ss = ssf.openSession();

        //4.执行映射配置文件sql语句，接收结果
        List<Student> list = ss.selectList("StudentMapper.selectAll");

        //5.处理结果
        for (Student stu : list) {
            System.out.println(stu);
        }

        //6.释放资源
        ss.close();
        is.close();
    }

    @Test
    public void selectById() throws Exception {
        InputStream is = Resources.getResourceAsStream("MybatisConfig.xml");

        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

        SqlSession sqlSession = sqlSessionFactory.openSession();

        Student stu = sqlSession.selectOne("StudentMapper.selectById", 3);

        System.out.println(stu);
        sqlSession.close();
        is.close();
    }



    @Test
    public void insert() throws Exception {
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");

        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);

        SqlSession sqlSession = sessionFactory.openSession(true);

        Student stu = new Student(5,"绘梨衣",19);
        int i = sqlSession.insert("StudentMapper.insert", stu);

        System.out.println(i);

        sqlSession.close();
        is.close();

    }

    @Test
    public void update() throws Exception {
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");

        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);

        SqlSession sqlSession = sessionFactory.openSession(true);

        Student stu = new Student(4,"天才",39);
        int i = sqlSession.update("StudentMapper.update", stu);

        System.out.println(i);

        sqlSession.close();
        is.close();
    }

    @Test
    public void delete() throws Exception {
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");

        SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(is);

        SqlSession sqlSession = ssf.openSession();

        int i = sqlSession.delete("StudentMapper.delete", 6);

        sqlSession.commit();
        System.out.println(i);

        sqlSession.close();
        is.close();

    }
}
